<template>
  <!-- el-form组件 elementUI插件里面的一个组件 经常展示表单元素
  model:用于收集表单数据 rules：表单验证规则
  -->
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
      label-position="left">
      <div class="title-container">
        <h3 class="title">登录</h3>
      </div>

      <el-form-item prop="userName">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="userName" v-model="loginForm.userName" placeholder="用户名" name="username" type="text" tabindex="1"
          auto-complete="on">
          <!-- <template #append>
            <el-select v-model="userType" style="width: 120px;">
              <el-option :label="管理员" value="管理员"></el-option>
              <el-option :label="会员" value="会员"></el-option>
            </el-select>
          </template> -->
        </el-input>
      </el-form-item>


      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="密码"
          name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>


      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;border-radius: 30px;"
        @click.native.prevent="handleLogin" :disabled="!canSubmit">登录</el-button>
    </el-form>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'

export default {
  name: 'Login',
  data() {
    // 进行表单验证 验证用户名和密码操作
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('密码长度不能小于4位'))
      } else {
        callback()
      }
    }
    return {
      userType: '管理员',
      loginForm: {
        userName: 'admin',
        password: '12345'
      },
      loginRules: {
        userName: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    userType(val) {
      if (val === "管理员") {
        this.loginForm.userName = 'admin'
        this.loginForm.password = 'admin'
        console.log("admin")
      } else if (val === "会员") {
        this.loginForm.userName = 'user'
        this.loginForm.password = 'user'
        console.log("user")
      }
    },
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
  },
  computed: {
    canSubmit() {
      const { userName, password } = this.loginForm
      return Boolean(userName && password)
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 登录业务：发送请求 带着用户名和密码给服务器 （成功与失败）
    handleLogin() {
      // 这里是在验证表单元素 （用户名与密码） 是否符合规则
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          await this.$API.user.login({ userName: this.loginForm.userName, password: this.loginForm.password })
            .then(res => {
              if (res.code === '0') {
                localStorage.setItem('token', res.msg);
                localStorage.setItem('userInfo', JSON.stringify(this.loginForm));
                // 1. 提示用户
                this.$message({
                  type: 'success',
                  message: '登录成功'
                })
                // 2. 跳转界面
                this.$router.replace({ path: '/' })
                // loading效果结束
                this.loading = false;
              }
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '账号或密码错误！'
              })
              this.loading = false;
            })
        }
        // 按钮会有一个loading效果
        // this.loading = true;
        // this.$store.dispatch('user/login', this.loginForm).then(() => {
        //   this.$message({
        //     type: 'success',
        //     message: '登录成功!'
        //   });
        //   // 注意 当前登录请求现在使用的是mock数据 mock数据code是20000
        //   // this.$router.push({ path: this.redirect || '/' })
        //   this.$router.replace({ path: '/' })
        //   // loading效果结束
        //   this.loading = false;
        // }).catch(() => {
        //   this.loading = false;
        // })
        // } else {
        //   console.log("error submit");
        //   return false;
        // }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {

  .el-form-item__content {
    height: 50px;
    background-color: #ffffff;
    border-radius: 5px;
  }

  .el-input {
    height: 47px;
    width: 93%;

    .el-select {
      position: absolute;
      right: 18px;
      top: 9px;
      height: 50px;
      border-radius: 5px;
      background-color: #f5f7fa;

    }

    input {
      color: black;
    }
  }

  input {
    background: transparent;
    border: 0px;
    -webkit-appearance: none;
    border-radius: 0px;
    padding: 12px 5px 12px 15px;
    color: $light_gray;
    height: 47px;
    caret-color: $cursor;

    &:-webkit-autofill {
      box-shadow: 0 0 0px 1000px $bg inset !important;
      -webkit-text-fill-color: $cursor !important;
    }
  }
}

.el-form-item {
  border: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  color: #454545;
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  position: relative;
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  background: url('../../assets/login.png');

  .login-form {
    width: 520px;
    max-width: 100%;
    padding: 220px 35px 0;
    margin: auto;
    overflow: hidden;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: black;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
